package com.run2code.design.behavioral.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 股票
 * 需要订阅主题
 *
 * @author lizongyang
 * @date 2024/06/17
 */
class Stock implements Subject {
    /**
     * 维护一个观察者列表
     */
    private final List<Observer> observers = new ArrayList<>();
    /**
     * 价格
     */
    private double price;

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void unregisterObserver(Observer observer) {
        System.out.println("移除观察者: " + ((Investor) observer).getName());
        observers.remove(observer);
    }

    @Override
    public void notifyObservers(double newPrice) {
        for (Observer observer : observers) {
            observer.update(newPrice);
        }
    }

    public void setPrice(double price) {
        this.price = price;
        // 价格变动后通知所有观察者
        notifyObservers(price);
    }

    public double getPrice() {
        return price;
    }
}
